package controller

import (
	"log"
	"user-go/entity"
	"user-go/vo"

	"github.com/androidsr/sc-go/model"
	"github.com/androidsr/sc-go/sgin"
	"github.com/androidsr/sc-go/sjwt"
	"github.com/androidsr/sc-go/sorm"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt"
)

const (
	SUCCESS    = 200
	AUTHORIZED = "Authorized"
	USER       = "userId"
	ROLE       = "roleId"
)

func init() {
	sgin.AddRouter(LoginController{})
}

type LoginController struct {
}

// 用户登录
// @Router [post] [/authorized]
func (LoginController) Authorized(c *gin.Context) any {
	user := struct {
		UserId string `json:"userId"`
		Passwd string `json:"passwd"`
	}{}
	c.BindJSON(&user)
	if user.UserId == "" || user.Passwd == "" {
		return model.NewFail(1001, "用户名或密码不能为空！")
	}
	data := new(entity.SysUsers)
	data.Account = user.UserId
	err := sorm.DB.GetOne(data)
	if err != nil {
		return model.NewFail(1001, "获取用户信息失败")
	}
	if data.State != "1" {
		return model.NewFail(1001, "账号已停用")
	}
	if data.Pass == "" || data.Pass != user.Passwd {
		return model.NewFail(1001, "账号或密码不正确！")
	}
	claims := jwt.MapClaims{}
	claims[USER] = data.Account
	claims[ROLE] = data.RoleId

	tokenStr, err := sjwt.GenerateToken(claims)
	if err != nil {
		log.Print(err)
		return model.NewFail(1001, "创建认证信息失败")
	}
	sjwt.SetWebToken(c, tokenStr)
	result := &vo.LoginResultVO{HttpResult: model.HttpResult{Code: 200, Msg: "登录成功"},
		Token: tokenStr, UserId: data.Account, UserName: data.Name}
	return result
}

// 修改密码
// @Router [put] [/repasswd]
func (LoginController) ResetPasswd(c *gin.Context) any {
	info := struct {
		UserId    string `json:"userId"`
		NewPasswd string `json:"newPasswd"`
		Passwd    string `json:"passwd"`
	}{}
	c.ShouldBind(&info)
	if info.UserId == "" || info.Passwd == "" || info.NewPasswd == "" {
		return model.NewFail(1001, "输入信息不完整")
	}
	data := new(entity.SysUsers)
	data.Account = info.UserId
	err := sorm.DB.SelectOne(data, data)
	if err != nil {
		return model.NewFail(1001, "获取用户信息失败")
	}

	if data.Pass != info.Passwd {
		return model.NewFail(1001, "账号或密码不正确！")
	}
	data.Pass = info.NewPasswd
	sorm.DB.UpdateById(data)
	return model.NewOK(nil)
}

// 用户注册
// @Router [post] [/register]
func (LoginController) Register(c *gin.Context, data *entity.SysUsers) any {
	data.RoleId = "61"
	sorm.DB.Insert(data)
	return model.NewOK(nil)
}

// 退出登录
func (LoginController) Logout(c *gin.Context) any {
	return model.NewOK(nil)
}
